package com.coderknock.bbs.login

import com.coderknock.bbs.service.UserService
import org.springframework.security.authentication.AuthenticationProvider
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.stereotype.Component

/**
 * <p>提供权限相关信息查询的功能</p>
 * @author 三产
 * @version 1.0
 * @date 2017-12-01
 * @QQGroup 213732117
 * @website http://www.coderknock.com
 * @copyright Copyright 2017 拿客 coderknock.com  All rights reserved.
 * @since JDK 1.8
 */
@Component
class CoderknockAuthenticationProvider(val userService: UserService) : AuthenticationProvider {
    override fun supports(authentication: Class<*>): Boolean {
        var flag = authentication == UsernamePasswordAuthenticationToken::class.java
        return flag
    }

    @Throws(AuthenticationException::class)
    override fun authenticate(authentication: Authentication): Authentication {
        val username = authentication.name
        val password = authentication.credentials.toString()
        try {
            val user = userService.loadUserByUsername(username)
            if (!userService.passwordEncoder.matches(password, user.password)) {
                throw BadCredentialsException("密码错误！")
            }

            val authorities = user.authorities
            return UsernamePasswordAuthenticationToken(user, password, authorities)
        } catch (e: Exception) {
            throw BadCredentialsException(e.message)
        }
    }
}